/*
 * @Author: 非幡动 438484791@qq.com
 * @Date: 2024-06-20 20:33:32
 * @LastEditors: 非幡动 438484791@qq.com
 * @LastEditTime: 2024-06-21 09:05:17
 * @FilePath: \vue-dicom-viewer-main\src\util\parsetxt.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 *  用于转换txt文件为我们所需要的数据
 */
// fileParser.ts
interface Slice {
  slice: number;
  leftX: number;
  leftY: number;
  rightX: number;
  rightY: number;
  centerPoint: { x: number; y: number };
  width: number;
  height: number;
}

interface ParsedData {
  spacing: number[];
  slices: Slice[];
}

const parseTXT = (contents: string): ParsedData => {
const lines = contents.split('\n');
const spacingLine = lines[0];
const spacing = spacingLine.match(/Spacing=\(([^)]+)\)/)?.[1].split(',').map(Number) || [];

const parsedData: ParsedData = {
  spacing: spacing,
  slices: [],
};

for (let i = 2; i < lines.length; i++) {
  const line = lines[i].trim();
  if (!line) {
    continue;
  }
  const [slice, leftX, leftY, rightX, rightY, centerPoint, width, height] = line.split(/\s+/);
  const [centerX, centerY] = centerPoint.replace(/[()]/g, '').split(',').map(Number);
  
  parsedData.slices.push({
    slice: Number(slice),
    leftX: Number(leftX),
    leftY: Number(leftY),
    rightX: Number(rightX),
    rightY: Number(rightY),
    centerPoint: { x: centerX, y: centerY },
    width: Number(width),
    height: Number(height),
    });
  }
  
  return parsedData;
};

const readFile = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.onload = (event) => {
    if (event.target) {
      const contents = event.target.result as string;
      resolve(contents);
    } else {
      reject(new Error('Failed to read file.'));
    }
  };
  reader.onerror = (event) => {
    reject(reader.error || new Error('Error reading file.'));
  };
  reader.readAsText(file);
});
};

export { parseTXT, readFile };
export type { ParsedData, Slice }
  